<template>
  <div class="template-categories">
    <el-tabs v-model="activeCategory">
      <el-tab-pane 
        v-for="category in categories" 
        :key="category.code"
        :label="category.name"
        :name="category.code"
      >
        <div class="template-grid">
          <div 
            v-for="template in categoryTemplates[category.code]"
            :key="template.id"
            class="template-card"
            @click="selectTemplate(template)"
          >
            <el-image :src="template.preview_image" />
            <div class="template-info">
              <h4>{{ template.name }}</h4>
              <p>{{ template.description }}</p>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useTemplateStore } from '@/stores/template';
import axios from 'axios';
import { useNotification } from '@/composables/useNotification';
import { io, Socket } from 'socket.io-client';

// 类型定义
interface Template {
  id: string;
  name: string;
  description: string;
  preview_image: string;
}

interface GenerationParams {
  prompt: string;
  parameters: Record<string, any>;
  templateId: string;
}

// 状态管理
const templateStore = useTemplateStore();
const activeCategory = ref('text2img');
const generationStatus = ref<string>('');
const generatedImage = ref<string>('');
const socket = ref<Socket | null>(null);
const { notify } = useNotification();

const categories = computed(() => templateStore.categories);
const categoryTemplates = computed(() => templateStore.getTemplatesByCategory);

// WebSocket 连接管理
const initWebSocket = () => {
  console.log('Initializing WebSocket connection...');
  socket.value = io(`${import.meta.env.VITE_API_URL}/generation`, {
    transports: ['websocket', 'polling']
  });
  
  socket.value.on('connect', () => {
    console.log('WebSocket connected, socket id:', socket.value?.id);
  });
  
  socket.value.on('generation_progress', (data) => {
    handleWebSocketMessage(data);
  });
  
  socket.value.on('generation_complete', (data) => {
    handleWebSocketMessage(data);
  });
  
  socket.value.on('error', (error) => {
    console.error('WebSocket error:', error);
    notify('error', '连接失败，请刷新页面重试');
  });
  
  socket.value.on('disconnect', () => {
    console.log('WebSocket disconnected');
  });
};

const handleWebSocketMessage = (data: any) => {
  console.log('Received WebSocket message:', data);
  
  switch (data.type) {
    case 'generation_progress':
      console.log(`Generation progress: ${data.progress}%`);
      generationStatus.value = `${data.progress}%`;
      break;
    case 'generation_complete':
      console.log('Generation completed:', data.imageUrl);
      generationStatus.value = '完成';
      generatedImage.value = data.imageUrl;
      break;
    case 'generation_error':
      console.error('Generation failed:', data.message);
      generationStatus.value = '失败';
      notify('error', data.message || '生成失败，请重试');
      break;
  }
};

const selectTemplate = (template: Template) => {
  templateStore.setCurrentTemplate(template);
};

const generateImage = async (params: GenerationParams) => {
  try {
    console.log('Sending generation request:', params);
    generationStatus.value = '准备中...';
    
    const { data } = await axios.post('/api/v1/generation/text2image', params);
    console.log('Generation task created:', data.taskId);
    
    if (socket.value?.connected) {
      console.log('Subscribing to task updates:', data.taskId);
      socket.value.emit('subscribe_task', { taskId: data.taskId });
    }
    
    return data.taskId;
  } catch (error) {
    console.error('Failed to start generation:', error);
    throw error;
  }
};

// 生命周期钩子
onMounted(() => {
  initWebSocket();
});

onUnmounted(() => {
  if (socket.value) {
    socket.value.disconnect();
  }
});
</script>

<style scoped>
.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  padding: 20px;
}

.template-card {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s;
}

.template-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.template-info {
  padding: 12px;
}
</style> 